<template>
  <div class="app-container">
    <div class="mainbox">
      <dt-table
        v-loading="loading"
        :table-opts="tableOpts"
        :is-column-search="false"
        :pagination-data="{
          total:total,
          queryParams:filterForm
        }"
        @pagination="pagination"
        @searchReset="handleReset"
        @searchChange="handleQuery"
        @handleSelectionChange="handleSelectionChange"
      >
        <template #toolbarBtn>
          <el-dropdown style="margin-left: 10px;">
            <el-button
              v-permission="['BASICDATA_EXPORT_BUTTON']"
              :disabled="tableOpts.tableData.length<=0"
            >导出<i class="el-icon-arrow-down el-icon--right" /></el-button>
            <el-dropdown-menu slot="dropdown" style="width:100px;text-align:center">
              <el-dropdown-item
                @click.native="handleDownload('all')"
                :disabled="tableOpts.tableData.length<=0"
              >导出所有</el-dropdown-item>
              <el-dropdown-item
                @click.native="handleDownload()"
                :disabled="tableOpts.tableData.length<=0"
              >导出选中</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button  style="margin-left: 10px" @click="handleImport" v-permission="['BASICDATA_IMPORT_BUTTON']">导入</el-button>
        </template>
      </dt-table>
      <dataItem ref="dataItemRef" />
      <dataEdit ref="dataEditRef" />

    </div>
    <dtDialog
      title="基础数据导入"
      :visible.sync="fileUploadVisible"
      width="620px"
      :is-loading="uploadLoading"
      @closeDialog="fileUploadVisible = false"
      @comfirmBtn="importDataSave"
    >
      <el-form slot="content">
        <div class="">
          <dt-importFile ref="dtImportFileRef" :down-load-template="handleImportTemplate" :type="fileName" />
        </div>
      </el-form>
    </dtDialog>
  </div>

</template>
<script>
// import bussinessUserAuthorizationApi from '@/framework/api/authCenter/bussinessUserAuthorization/bussinessUserAuthorization'
import dataItem from './components/dataItem.vue'
import dataEdit from './components/dataEdit.vue'
import { basicMaterialTypePage, basicMaterialTypeDelete, uploadFile, downloadTemplate, exportMaterialType, exportAll } from '@/framework/api/developerCenter/basicData'
import { dateTimeFormat } from '@/framework/utils/dateTime'

export default {
  name: 'BasicData',
  dicts: ['sex'],
  components: { dataItem, dataEdit },
  data() {
    return {
      radio1: '全部',
      cardindex: 0,
      personId: '',
      cardShow: false,
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 查询参数
      filterForm: {
        materialTypeCode: '',
        materialTypeName: '',
        pageNo: 1,
        pageSize: 10
      },
      tableOpts: {
        rowKey: 'id',
        tableData: [],
        customSearch: [{
        }],
        toolbarBtn: [
          {
            label: '新增',
            permission: ['BASICDATA_ADD_BUTTON'],
            icon: 'el-icon-plus',
            type: 'primary',
            size: 'medium',
            click: () => {
              this.handleAdd()
            }
          }
          // {
          //   label: '导出',
          //   click: () => {
          //     this.handleDownload()
          //   }
          // }, {
          //   label: '导入',
          //   click: () => {
          //     this.handleImport()
          //   }
          // }
        ],
        // 表格第一列
        indexTableCol: {
          label: '序号',
          width: 70
        },
        tableCol: [
          {
            prop: 'materialTypeCode',
            label: '数据类编码',
            show: true,
            align: 'left'
          },
          {
            prop: 'materialTypeName',
            label: '数据类名称',
            show: true,
            search: true,
            align: 'left',
            labelWidth: '90px'
          },
          {
            prop: 'enable',
            label: '启用状态',
            show: true,
            search: true,
            align: 'left',
            searchType: 'select',
            formatter: (row) => { return row.enable == 1 ? '启用' : '禁用' },
            searchData: () => {
              return [
                { label: '启用', value: 1 },
                { label: '禁用', value: 0 }
              ]
            }
          },
          {
            prop: 'remark',
            label: '描述',
            show: true,
            align: 'left'
          },
          {
            prop: 'createUser',
            label: '创建人',
            show: true,
            align: 'left'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            show: true,
            align: 'left',
            disabled: true
          }
        ],
        operator: {
          width: 260,
          align: 'left',
          operatorBtn: [
            {
              text: '查看数据项',
              permission: ['BASICDATA_SEEDATA_BUTTON'],
              size: 'small',
              // disabledChange: (row) => { return row.superAdminFlag == 'Y' },
              click: (row, col, cellValue) => { return this.openDrawer(row) }
            },
            {
              text: '编辑',
              permission: ['BASICDATA_UPDATE_BUTTON'],
              size: 'small',
              // disabledChange: (row) => { return row.superAdminFlag == 'Y' },
              click: (row, col, cellValue) => { return this.handleEdit(row) }
            },
            {
              text: '删除',
              permission: ['BASICDATA_DEL_BUTTON'],
              size: 'small',
              type: 'danger',
              // disabledChange: (row) => { return row.superAdminFlag == 'Y' },
              click: (row, col, cellValue) => { return this.handleDelete(row) }
            }
          ]
        }
      },
      fileUploadVisible: false,
      uploadLoading: false,
      handleImportTemplate: downloadTemplate,
      fileName: '数据类导入',
      multipleSelection: []

    }
  },
  watch: {
    fileUploadVisible: {
      handler(n, o) {
        if (!n) {
          this.$nextTick().then(() => {
            this.$refs.dtImportFileRef.fileList = []
          })
        }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 新增按钮
    handleAdd() {
      this.$refs.dataEditRef.handleData('', 'add')
    },
    // 修改按钮
    handleEdit(row) {
      this.$refs.dataEditRef.handleData(row, 'update')
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$dtModal.confirm(`是否确认删除"${row.materialTypeName}"吗？删除后，引用该数据类的历史数据展示时将直接展示数据类编码`).then(() => {
        // 删除接口
        return basicMaterialTypeDelete({ ids: [row.id] })
      }).then(() => {
        this.getList()
        this.$dtModal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    getList() {
      this.loading = true
      basicMaterialTypePage(this.filterForm).then((res) => {
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery(formModel) {
      this.filterForm = { ...this.filterForm, ...formModel }
      this.filterForm.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.filterForm = {
        materialTypeCode: '',
        materialTypeName: '',
        // enable: '1',
        pageNo: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    pagination() {
      this.getList(this.filterForm)
    },
    openDrawer(row) {
      this.$refs.dataItemRef.handleOpen(row)
    },
    handleImport() {
      this.fileUploadVisible = true
    },
    // 导入
    importDataSave() {
      const file = this.$refs.dtImportFileRef.fileList
      if (file.length == 0) {
        this.$dtMessage({
          title: '失败',
          message: '请选择需要上传的文件',
          type: 'error',
          duration: 2000
        })
        return
      }
      const formData = new FormData()
      // 数据
      formData.append('file', file[0].raw)
      formData.append('name', file[0].name)
      uploadFile(formData).then(async (res) => {
        this.uploadLoading = true
        this.fileUploadVisible = false
        if (res.data.errorDownloadPath) {
          this.$alert(`<div> <div class="title">${res.data.tip}</div> <div class="content"><span class="btn" id="messageBtn" style="color:#5688E8;cursor:pointer">点击下载导入失败的信息</span> </div> </div>`, '导入完成', {
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$alert(`<div> <div class="title">${res.data.tip}导入完成`, {
            dangerouslyUseHTMLString: true
          })
        }
        this.getList()
        await this.$nextTick()
        document.getElementById('messageBtn').onclick = function () {
          window.location.href = res.data.errorDownloadPath
        }
        this.uploadLoading = false
      }).catch((res) => {
        this.uploadLoading = false
      })
    },
    // 导出
    handleDownload(type) {
      let con = {}
      if (type == 'all') {
        this.showScreenLoading()
        exportAll().then((res) => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          const fileType = res.headers['content-disposition'].substring(res.headers['content-disposition'].lastIndexOf('.') + 1).toLowerCase()
          const nowDateTime = dateTimeFormat()
          a.download = `数据类导出信息${nowDateTime}.${fileType}` // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }).catch((res) => {
          this.hideScreenLoading()
        })
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请至少选择一项',
            type: 'error',
            duration: 2000
          })
          return
        }
        const ids = this.multipleSelection.map((res) => {
          return res.id
        })
        con = {
          ids
        }
        this.showScreenLoading()
        exportMaterialType(con).then((res) => {
          if (this.tableOpts.tableData == null) {
            this.$dtMessage({
              title: '失败',
              message: res.message,
              type: 'error',
              duration: 2000
            })
          } else {
            const blob = new Blob([res.data], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            const objectUrl = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.style.display = 'none'
            a.href = objectUrl // 指定下载链接
            // a.download = '基础数据' // 指定下载文件名
            const fileType = res.headers['content-disposition'].substring(res.headers['content-disposition'].lastIndexOf('.') + 1).toLowerCase()
            const nowDateTime = dateTimeFormat()
            a.download = `数据类导出信息${nowDateTime}.${fileType}` // 指定下载文件名
            a.click()
            URL.revokeObjectURL(a.href) // 释放URL对象
            this.hideScreenLoading()
          }
        }).catch((res) => {
          this.hideScreenLoading()
        })
      }
    }
  }
}
</script>
<style scoped lang="scss">
.createUserDiv {
  display: flex;
  align-items: center;
  cursor: pointer;
  ::v-deep .el-avatar--small.name-circle {
    width: 28px;
    height: 28px;
    background: linear-gradient(180deg, #B8E24B 0%, #129A37 100%);
    margin-right: 8px;
  }
}
.radiobox{
  margin-left: 20px;
  margin-bottom: 8px;
}
</style>

